package com.sxpi.zixun.config.interceptor;

import com.sxpi.zixun.common.anno.IgnoreToken;
import com.sxpi.zixun.common.enums.AdminUserResultEnum;
import com.sxpi.zixun.common.ex.PugValidatorException;
import com.sxpi.zixun.common.utils.fn.asserts.Vsserts;
import com.sxpi.zixun.service.jwt.JwtService;
import com.sxpi.zixun.config.redis.AdminRedisKeyManager;
import com.sxpi.zixun.config.redis.IJwtBlackService;
import com.sxpi.zixun.local.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 挤下线使用
 * @author 蓝欣
 */
@Component
@Slf4j
public class PassportLogoutInterceptor implements HandlerInterceptor, AdminRedisKeyManager {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    @Qualifier(value = "jwtBlackStringService")
    private IJwtBlackService iJwtBlackService;

    @Autowired
    private JwtService jwtService;

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        Class<?> beanType = handlerMethod.getBeanType();
        IgnoreToken annotationMethod = method.getAnnotation(IgnoreToken.class);
        IgnoreToken annotationClass = beanType.getAnnotation(IgnoreToken.class);
        // 方法级别和方法级别的判断
        if(annotationMethod != null || annotationClass != null){
            return true;
        }
        // 判断当前的token是不是一个退出的token，如果存在黑名单直接返回过期或者无效
        String token = jwtService.getToken(request);
        if(iJwtBlackService.isBlackList(token)){
            throw new PugValidatorException(AdminUserResultEnum.TOKEN_NOT_FOUND);
        }
        // 获取用户传递过来的token_uuid
        String tokenUuid = request.getHeader(TOKEN_UUID);
        Vsserts.isEmptyEx(tokenUuid,AdminUserResultEnum.USER_LOGIN_UUID_EMPTY);
        // 从redis获取用户uuid
        String tokenUserid = request.getHeader(TOKEN_USER_ID);
        String tokenUuidKey = USER_LOGOUT_TOKEN_KEY + tokenUserid;
        String cacheUuid = redisTemplate.opsForValue().get(tokenUuidKey);
        Vsserts.isEmptyEx(cacheUuid,AdminUserResultEnum.USER_LOGIN_UUID_EMPTY);
        // 如果与缓存的uuid不同，就说明异地登录了
        if(!tokenUuid.equalsIgnoreCase(cacheUuid)){
            throw new PugValidatorException(AdminUserResultEnum.USER_LOGIN_SAME);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
